package test.algorithm.FastSlowPointer;

/**
 * 折半查找（二分查找）
 * @author serenity
 *
 */
public class BinarySearch {
	
	/**
	 * 折半查找 
	 * 返回元素位置，没找到返回-1
	 * @param data
	 * @param s
	 * @return
	 */
	public static int binarySearch(int[] data , int s){
		int low = 0;
		int high = data.length-1;
		int mid = (high+low)/2;
		int flag = -1;
		int count = 0;
		
		while(low<=high){
			count++;
			mid = (high+low)/2;
			
			if(s<data[mid]){
				//待查找值s小于中值
				high = mid-1;
			}else if(s>data[mid]){
				//待查找值s大于中值
				low = mid+1;
			}else{
				//待查找值s等于中值
				flag = mid;
				break;
			}
		}
		System.out.println("查找次数："+count); 
		return flag;
	}

	public static void main(String[] args) {
		int[] data = {1,2,3,4,5,6,7,8,9,10};
		System.out.print("数组:");
		for(int i : data){
			System.out.print(i+" ");
		}
		System.out.println();
		int search = 4;
		int position = binarySearch(data,search);
		System.out.println("值"+search+"的元素位置为："+position);
	}

}
